<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Terminal</title>
    <link rel="stylesheet" href="../static/css/xterm.css" />
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <script src="../static/js/xterm.js"></script>
    <script src="../static/js/xterm-addon-fit.js"></script>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            background-color: transparent;
        }
        #terminal {
            border-bottom-left-radius: 4px;
            border-bottom-right-radius: 4px;
            height: 100%;
            padding: 0;
            margin: 0;
            background-color: transparent;
            overflow: hidden;
        }
        .context-menu {
            position: fixed;
            background: #fff;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            padding: 5px 0;
            z-index: 1000;
        }
        .context-menu-item {
            padding: 5px 15px;
            cursor: pointer;
            user-select: none;
        }
        .context-menu-item:hover {
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <div id="terminal"></div>
    <div id="context-menu" class="context-menu" style="display: none;">
        <div class="context-menu-item" id="copy-menu">复制</div>
        <div class="context-menu-item" id="paste-menu">粘贴</div>
    </div>
    <script>
        let term = null;

        // 统一的日志记录函数
        function logToFile(message) {
            try {
                if (window.terminal) {
                    const formattedMessage = `[JavaScript] ${message}`;
                    window.terminal.logToFile(formattedMessage);
                } else {
                    console.warn('Terminal对象未初始化，无法记录日志');
                }
            } catch (error) {
                console.error('日志记录失败:', error);
            }
            console.log(message); // 保留控制台输出用于调试
        }

        // 处理右键菜单
        function handleContextMenu(e) {
            e.preventDefault();
            const menu = document.getElementById('context-menu');
            const hasSelection = term && term.hasSelection();
            
            menu.style.display = 'block';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';

            // 根据是否有选中文本来启用/禁用复制菜单
            document.getElementById('copy-menu').style.opacity = hasSelection ? '1' : '0.5';
            document.getElementById('copy-menu').style.cursor = hasSelection ? 'pointer' : 'not-allowed';
        }

        // 复制选中文本
        function copySelectedText() {
            logToFile(`term: ${term}`);
            logToFile(`termSelection: ${term.hasSelection()}`);
            logToFile(`term.getSelection(): ${term.getSelection()}`);

            if (term && term.hasSelection()) {
                const selectedText = term.getSelection();
                try {
                    if (!selectedText) {
                        logToFile('没有选中任何文本');
                        return;
                    }
                    logToFile('使用Qt剪贴板API复制文本...');
                    // 使用Qt的剪贴板API
                    window.terminal.copyToClipboard(selectedText);
                    // 添加视觉反馈
                    const copyMenu = document.getElementById('copy-menu');
                    const originalText = copyMenu.textContent;
                    copyMenu.textContent = '已复制';
                    setTimeout(() => {
                        copyMenu.textContent = originalText;
                        closeContextMenu();
                    }, 1000);
                } catch (err) {
                    logToFile(`复制失败: ${err.message}`);
                    alert('复制失败，请尝试使用快捷键 Ctrl+C/Command+C');
                }
            }
        }

        // 粘贴文本
        async function pasteText() {
            try {
                // 使用Qt的剪贴板API
                const text = await window.terminal.pasteFromClipboard();
                if (term && text) {
                    // 确保text是字符串类型
                    const safeText = typeof text === 'string' ? text : String(text);
                    term.paste(safeText);
                    logToFile('文本已粘贴');
                }
            } catch (err) {
                logToFile(`粘贴失败: ${err.message}`);
            }
        }

        // 点击其他地方关闭菜单
        function closeContextMenu() {
            document.getElementById('context-menu').style.display = 'none';
        }

        function initTerminal() {
            // 确保QWebChannel先初始化
            try {
                if (!qt || !qt.webChannelTransport) {
                    logToFile('错误：Qt WebChannel transport not available');
                    return;
                }
                
                new QWebChannel(qt.webChannelTransport, function(channel) {
                    if (!channel || !channel.objects || !channel.objects.terminal) {
                        logToFile('错误：Terminal object not available in channel');
                        return;
                    }
                    
                    window.terminal = channel.objects.terminal;
                    logToFile('QWebChannel初始化成功');
                    logToFile(`Terminal对象: ${JSON.stringify(window.terminal)}`);
                    
                    // 等待xterm.js和相关插件加载完成
                    const checkDependencies = () => {
                        if (typeof Terminal === 'undefined' || typeof FitAddon === 'undefined') {
                            setTimeout(checkDependencies, 100);
                            return;
                        }
                        initXterm();
                    };
                    
                    checkDependencies();
                    
                    // 注册接收数据的处理函数
                    window.terminal.dataReceived.connect(function(data) {
                        if (term) {
                            term.write(data);
                        }
                    });
                });
            } catch (error) {
                logToFile(`错误：QWebChannel初始化失败: ${error.message}`);
            }
        }

        function initXterm() {
            // 初始化xterm.js终端
            logToFile('开始初始化xterm.js终端');
            window.terminal.loadTerminalConfig().then(config => {
                logToFile(`加载配置文件: ${config}`);
                term = new Terminal({
                    ...JSON.parse(config)
                });
                
                const fitAddon = new FitAddon.FitAddon();
                term.loadAddon(fitAddon);
                
                logToFile('打开终端并应用FitAddon');
                term.open(document.getElementById('terminal'));
                fitAddon.fit();
                term.focus();  // 自动聚焦到终端
                
                // 监听窗口大小变化
                window.addEventListener('resize', () => {
                    fitAddon.fit();
                });
                
                // 监听用户输入
                term.onData(data => {
                    try {
                        if (!window.terminal) {
                            logToFile('错误：QWebChannel未初始化');
                            return;
                        }
                        
                        // 处理退格键
                        if (data === '\x7f') {
                            window.terminal.sendData('\b');
                            return;
                        }
                        
                        // 如果是回车键，记录当前命令
                        if (data === '\r') {
                            const currentLine = term.buffer.active.getLine(term.buffer.active.cursorY);
                            let command = '';
                            for (let i = 0; i < currentLine.length; i++) {
                                command += currentLine.getCell(i).getChars();
                            }
                            command = command.trim();
                            if (command) {
                                window.terminal.logCommand(command);
                            }
                        }
                        
                        window.terminal.sendData(data);
                    } catch (error) {
                        logToFile(`错误：发送数据失败: ${error.message}`);
                    }
                });

                // 监听光标位置变化
                term.onCursorMove(() => {
                    try {
                        if (window.terminal) {
                            const pos = term.buffer.active.cursorY + 1;
                            const col = term.buffer.active.cursorX + 1;
                            window.terminal.updateCursorPosition(pos, col);
                        }
                    } catch (error) {
                        logToFile(`错误：更新光标位置失败: ${error.message}`);
                    }
                });
                
                logToFile('xterm.js初始化成功');

                // 添加右键菜单事件监听
                document.getElementById('terminal').addEventListener('contextmenu', handleContextMenu);
                document.addEventListener('click', closeContextMenu);
                document.getElementById('copy-menu').addEventListener('click', copySelectedText);
                document.getElementById('paste-menu').addEventListener('click', pasteText);
            }).catch(error => {
                logToFile(`错误：加载终端配置失败: ${error.message}`);
            });
        }

        // 初始化终端
        initTerminal();
    </script>
</body>
</html>